<?php
/**
 * Created by PhpStorm.
 * User: surface
 * Date: 2018/12/16
 * Time: 18:26
 */
namespace app\Manage\controller;
use app\common\controller\Manage;
use app\common\model\RoomBooking as BookingModel;
use Request;
use app\common\model\BillPayments as BillPaymentsModel;
use app\common\model\Payments as PaymentsModel;
use app\common\model\Balance as BalanceModel;
use app\common\model\User as UserModel;

class Booking extends Manage{

    public function index()
    {
        $bookingModel = new BookingModel();
        if (Request::isAjax()) {
            $filter              = input('request.');
            return $bookingModel->tableData($filter);
        }
        return $this->fetch('index');
    }

    public function add()
    {
        $this->view->engine->layout(false);
        return $this->fetch();
    }

    public function to_shop()
    {
        $bookingModel = new BookingModel();
        return $bookingModel->to_shop(input('param.id/d'));
    }

    public function  doAdd(){
        $bookingModel = new BookingModel();
        return $bookingModel->addData(input('param.'));
    }

    public function edit()
    {
        $this->view->engine->layout(false);
        $bookingModel = new BookingModel();
        if(Request::isPost())
        {
            $data = input('param.');
            $data['taocan'] = $this->getTaoCan($data['room_id'], $data['taocan']);
            //print_r($data);exit;
            return $bookingModel->saveData($data);
        }
        $data = $bookingModel->where('id',input('param.id/d'))->find();
        if (!$data) {
            return error_code(10002);
        }
        $data['booking_time'] = date('Y-m-d', $data['booking_time']);
        $data['taocan'] = json_decode($data['taocan'], true);
        return $this->fetch('edit',['data' => $data]);
    }
    private function getTaoCan($room_id, $no) {
        $roomModel = new \app\common\model\Room();
        $taocan_info = $roomModel->where('id', $room_id)->field('id,taocan')->find();
        $taocan_info->taocan = json_decode($taocan_info->taocan, true);
        if(!is_array($taocan_info->taocan )) {
            $taocan_info->taocan = json_decode($taocan_info->taocan, true);
        }
        $new_data = [];
        foreach($taocan_info->taocan as $taocan) {
            $new_data[$taocan['no']] = $taocan; 
        }
        return json_encode($new_data[$no], JSON_UNESCAPED_SLASHES);
    }

    public function getBooking(){
        $result = [
            'status' => true,
            'msg' => '获取成功',
            'data'=> []
        ];
        $bookingModel = new BookingModel();
        $booking = $bookingModel->field('*')->where(['id'=>input('param.id/d')])->find();
        $userModel = new UserModel();
        $user = $userModel->field('*')->where(['id' => $booking['user_id']])->find();
        $booking['nickname'] = $user['nickname'];
        $result['data'] = $booking;
        return $result;
    }

    public function cancel(){
        $res = $this->validate(['__token__' => input('token')], ['__token__'  =>  'require|token']);
        if($res !== true) { 
            return json([
                'status' => false,
                'data' => '',
                'msg' => $res,
            ], 400); 
        }
        $result = [
            'status' => true,
            'msg' => '修改成功',
            'data'=> []
        ];
        $bookingModel = new BookingModel();
        $booking = $bookingModel->field('*')->where(['id'=>input('param.id/d')])->find();
        if($booking['pay_status'] == 2){
            return $result;
        }
        ///到店不能退款
        //if($booking['to_shop'] != 0){
        if($this->request->post('isrefund')) {
           if($booking['pay_status'] == 1){
               $billPaymentsModel = new BillPaymentsModel();
               $info = $billPaymentsModel->getSuccessPaymentInfo(input('param.id/d'), 4);

               $paymentsModel = new PaymentsModel();
               $paymentInfo = $paymentsModel->getPayment($booking['payment_code'], $paymentsModel::PAYMENT_STATUS_YES);
               $conf = json_decode($paymentInfo['params'], true);

               if($booking['payment_code'] == 'balance'){
                   $balanceModel = new BalanceModel();
                   $balanceModel->change($booking['user_id'],2, $booking['price'], $booking['id']);
               }else{
                   $payment = \org\Payment::create($booking['payment_code'], $conf);       //'wechatpay' or alipa
                   $res = $payment->refund($info['trade_no'], $booking['price']);
               }
           }
        }
       // }
        $bookingModel->save(['pay_status'=> 2,'to_shop'=>0, 'isrefund' => $this->request->post('isrefund')],['id'=>input('param.id/d')]);
        return $result;
    }

    public function clean(){
        $result = [
            'status' => true,
            'msg' => '修改成功',
            'data'=> []
        ];
        $bookingModel = new BookingModel();
        $bookingModel -> save(['to_shop'=>2],['id'=>input('param.id/d')]);
        return $result;
    }

}